package org.example.utils

import org.example.client.DbClient
import org.example.constant.ApolloConst

import java.sql.DriverManager
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.util.control.Exception.ignoring

/**
 * hive工具类
 */
object HIVEUtil {


  /**
    * 获取hive表的字段 王建成
    * @param database hive库
    * @param tableNames hive表
    * @return
    */
  def getColsByTable(database:String,tableNames:ArrayBuffer[String]):  mutable.HashMap[String, ArrayBuffer[String]] ={
    var tableColMap = scala.collection.mutable.HashMap("" -> new ArrayBuffer[String]())
    DbClient.init("hive", ApolloConst.hiveDriver, ApolloConst.hiveURL, ApolloConst.hiveUserName, ApolloConst.hivePassWord)
    DbClient.usingDB("hive") { db =>
      val connection = db.conn
      val metaData = connection.getMetaData
      if (database!=null && database.trim.nonEmpty && tableNames!=null && tableNames.nonEmpty){
        tableNames.foreach{tableName=>
          val rs = metaData.getColumns(null, database, tableName, "%")
          val cols = new ArrayBuffer[String]()
          while (rs.next()) {
            val column = rs.getString("column_name")
            cols += column
          }
          tableColMap += (tableName -> cols)
        }
      }
    }
    tableColMap
  }

  /**
    * 获取hive表的字段  刘建红
    * @param database hive库
    * @param tableNames hive表
    * @return
    */
  def getFieldsByTable(database:String,tableNames:ArrayBuffer[String]):  mutable.HashMap[String, ArrayBuffer[String]] ={
    var tableColMap = scala.collection.mutable.HashMap("" -> new ArrayBuffer[String]())
    Class.forName(ApolloConst.hiveDriver)
    val connection = DriverManager.getConnection(ApolloConst.hiveURL, ApolloConst.hiveUserName, ApolloConst.hivePassWord)
    try{
      val metaData = connection.getMetaData
      if (database!=null && database.trim.nonEmpty && tableNames!=null && tableNames.nonEmpty) {
        tableNames.foreach { tableName =>
          val rs = metaData.getColumns(null, database, tableName, "%")
          val cols = new ArrayBuffer[String]()
          while (rs.next()) {
            val column = rs.getString("column_name")
            cols += column
          }
          tableColMap += (tableName -> cols)
        }
      }
    }finally {
      ignoring(classOf[Throwable]) apply connection.close()
    }

    tableColMap
  }


}
